/**
 * 单词本列表页面
 * @author 杨世峰
 */

<template>
  <div class="booklet-list-container">
    <div class="booklet-list-inner" style="margin-left: 300px; margin-right: 300px">
      <el-table :data="tableData" style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }">
        <el-table-column prop="createDate" label="日期" sortable width="auto">
        </el-table-column>
        <el-table-column prop="bookletName" label="单词本名称" sortable width="auto">
        </el-table-column>
        <el-table-column fixed="right" label="查看" width="120">
          <template slot-scope="scope">
            <el-button @click="handleBookletDetail(scope.$index, tableData)" type="text" size="small">
              查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="学习" width="120">
          <template slot-scope="scope">
            <el-button @click="handleLearn(scope.$index, tableData)" type="text" size="small">
              进入学习
            </el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="分享" width="120">
          <template slot-scope="scope">
            <el-button @click="handleShare(scope.$index, tableData)" type="text" size="small">
              分享单词本
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tabListPage">
        <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="PageSize"
          layout="prev, pager, next, jumper">
        </el-pagination>
      </div>
      <div style="float: right">
        <el-button type="primary" @click="handleCreateBooklet">创建新的单词本</el-button>
      </div>
    </div>

    <div>
      <el-dialog :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
        <el-descriptions>
          <el-descriptions-item label="单词本名称">{{
              bookletDetail.bookletName
          }}</el-descriptions-item>
          <el-descriptions-item label="单词本作者">{{
              bookletDetail.bookletAuthor
          }}</el-descriptions-item>
          <el-descriptions-item label="单词本描述">{{
              bookletDetail.bookletIntro
          }}</el-descriptions-item>
          <el-descriptions-item label="单词总数">
            <el-tag size="small">{{ bookletDetail.bookletEntryCount }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="已经学习的单词数">{{
              bookletDetail.bookletEntryLearnedCount
          }}</el-descriptions-item>
          <el-descriptions-item label="未学习的单词总数">{{
              bookletDetail.bookletEntryUnLearnedCount
          }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
              bookletDetail.bookletCreateDate
          }}</el-descriptions-item>
        </el-descriptions>

        <el-table :data="currentEntries.list" style="width: 100%"
          :default-sort="{ prop: 'lastLearnedTime', order: 'descending' }">
          <el-table-column prop="wordSpell" label="单词拼写" sortable width="auto"></el-table-column>
          <el-table-column prop="learnedCount" label="学习次数" sortable width="auto"></el-table-column>
          <el-table-column prop="lastLearnedTime" label="上次学习时间" sortable width="auto"></el-table-column>
        </el-table>
        <el-pagination @current-change="handleEntryCurrChange" :current-page="currentEntries.page"
          :page-size="currentEntries.pageSize" layout="total, prev, pager, next, jumper">
        </el-pagination>

        <span slot="footer" class="dialog-footer">
          <el-button type="danger" @click="handleDeleteCurBooklet" style="float:left">删除</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog :visible.sync="bookletFormatVisible" width="60%" :before-close="handleClose">
        <el-form :inline="true" :model="bookletForm" class="demo-form-inline">
          <el-form-item label="单词本名称">
            <el-input v-model="bookletForm.name" placeholder="单词本名称"></el-input>
          </el-form-item>
          <el-form-item label="单词本简介">
            <el-input v-model="bookletForm.introduction" placeholder="单词本简介"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handlePostBooklet">创建单词本</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {
  getUserBooklets,
  getBookletDetail,
  getBookletEntries,
  createBooklet,
  deleteBooklet,
} from "@/api/user/bookletApi.js";

import { shareBooklet } from "@/api/user/shareBookletApi.js";
export default {
  data() {
    return {
      tableData: [],
      currentPage: 1,
      totalCount: 1,
      PageSize: 10,
      dialogVisible: false,
      bookletFormatVisible: false,
      bookletDetail: {},
      currentBookletId: NaN,
      currentEntries: {
        page: 1,
        pageSize: 10,
      },
      bookletForm: {
        name: "",
        introduction: "",
      },
    };
  },
  computed: {
    userId() {
      return this.$store.getters.userId;
    },
    roleId() {
      return this.$store.getters.roleId
    }
  },
  methods: {
    getData(page, pageSize) {
      getUserBooklets(this.userId == undefined ? 1 : this.userId, {
        page: page,
        pageSize: pageSize,
      })
        .then((res) => {
          console.log(res);
          // 这里处理后端返回的结果
          this.tableData = res.data.list;
          this.currentPage = res.data.page;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getBookletDetai(index, tableData) {
      getBookletDetail(tableData[index].bookletId)
        .then((res) => {
          console.log(res);
          this.bookletDetail = res.data;
        })
        .catch();
    },

    getEntries(index, tableData, pageNum, pageSize) {
      getBookletEntries(tableData[index].bookletId, {
        page: pageNum,
        pageSize: pageSize,
      })
        .then((res) => {
          this.currentEntries = res.data;
        })
        .catch();
    },

    // 显示第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData(val, this.PageSize);
    },

    handleBookletDetail(index, tableData) {
      this.dialogVisible = true;
      this.currentBookletId = tableData[index].bookletId;

      this.getBookletDetai(index, tableData);

      this.getEntries(
        index,
        tableData,
        this.currentEntries.page,
        this.currentEntries.pageSize
      );
    },

    handleClose(done) {
      done();
    },

    handleEntryCurrChange(val) {
      getBookletEntries(this.currentBookletId, {
        page: val,
        pageSize: this.currentEntries.pageSize,
      })
        .then((res) => {
          this.currentEntries = res.data;
        })
        .catch();
    },

    // 处理创建新的单词本
    handleCreateBooklet() {
      // 1 使表单窗口显性
      this.bookletFormatVisible = true;
    },

    // 创建单词本成功消息弹窗
    alertCreateBooklet(res) {
      this.$notify({
        title: "成功",
        message: res.message,
        type: res.resultCode === 200 ? "success" : "warning",
      });
    },

    handlePostBooklet() {
      // 2 获取表单内容、验证、发送请求
      console.log(this.bookletForm);
      this.bookletForm.userId = Number(this.userId);
      createBooklet(this.bookletForm)
        .then((res) => {
          this.bookletFormatVisible = false;
          this.alertCreateBooklet(res);
          console.log(res);

          // 重新执行获取单词本列表的方法
          this.getData(this.currentPage, this.PageSize);

          // 清空表单
          Object.keys(this.bookletForm).forEach((key) => {
            this.bookletForm[key] = "";
          });
        })
        .catch((err) => console.log(err));
    },

    // 删除当前单词本
    handleDeleteCurBooklet() {
      // 二次确认
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 发送删除请求
          deleteBooklet(this.currentBookletId)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: res.message,
                type: res.resultCode === 200 ? "success" : "warning",
              });
              this.getData(this.currentPage, this.PageSize);
            })
            .catch();
        })
        .catch(() => { })
        .then(() => {
          this.dialogVisible = false;
        });
    },

    handleLearn(tableIndex, tableData) {
      let bookletId = tableData[tableIndex].bookletId;
      if (this.roleId == 2) {
        this.$router.push({
        name: "LearnWords",
        params: { bookletId: bookletId },
      }).catch(() => { });
      } else if (this.roleId == 1) {
        this.$router.push({
        name: "LearnWordsAdmin",
        params: { bookletId: bookletId },
      }).catch(() => { });
      }

    },

    handleShare(tableIndex, tableData) {
      let bookletId = tableData[tableIndex].bookletId;
      shareBooklet(bookletId)
        .then((res) => {
          if (res.resultCode == 200) {
            this.$notify({
              title: "成功",
              message: res.message,
              type: "success",
            });
          } else {
            this.$notify({
              title: "失败",
              message: res.message,
              type: "warning",
            });
          }
        })
        .catch();
    },
  },

  created: function () {
    this.getData(this.currentPage, this.PageSize);
  },
};
</script>

<style lang="scss" scoped>
.booklet-list-container {
  margin-top: 80px;
}

.booket-name {
  color: aqua;
}
</style>